import express from "express";
import { getDate } from "../lib/time.mjs";
import dbTool from "../lib/DbUtil.mjs";
const app = express();
app.listen(8062);

/**
 * @exp32 /esp32/getcmd
 * - 服务器应返回
 * - 从cmd表中查询到的信息
 */
app.get("/esp32/getcmd", (req, res) => {
	console.log("————————————Respond———esp32_getcmd—————————————————————————");
	dbTool.query(
		"select cmd_id,val_1,val_2,val_3 from `cmd` limit 0,1",
		(data) => {
			console.log("查得 cmd：" + JSON.stringify(data[0]));
			res.json(data[0]);
		}
	);
	console.log("——————————————————Over———————————————————————————————————————");
});
/**
 * @exp32 /esp32/putsignal
 * - 服务器从 query 中获取 val_1 2 3
 * - esp32发送信号信息
 */
app.get("/esp32/putsignal", (req, res) => {
	let query = req.query;
	console.log(query);
	res.send("esp32 正在更新最近收到的信号消息");
});
/**
 * @exp32 /esp32/finishcmd
 * - 服务器明白esp32完成了cmd任务
 * - 服务器更新cmd表（delete）
 */
app.get("/esp32/finishcmd", (req, res) => {
	let cmd_id = req.query.id || -1;
	if (cmd_id == -1) {
		console.error("异常的cmd_id: " + cmd_id);
		res.end();
	} else {
		dbTool.del("delete from `cmd` where cmd_id=?", [cmd_id], (result) => {
			if (result.affectedRows > 0) {
				console.log("删除成功：" + cmd_id);
				res.send("删除成功：" + cmd_id);
			} else {
				res.send("Unexpected ERROR");
			}
		});
	}
});

/**
 * @flutter /flutter/getshow
 * - 服务器应返回
 * - 最近收到的信息
 * - 即 表dones 的最近信息
 */
app.get("/flutter/getshow", (req, res) => {
	res.send("/flutter/getshow");
});
/**
 * @flutter /flutter/setcmd
 * - 服务器从 query 获取信号信息 val_1 2 3
 * - 并设置该信号为下一条cmd
 */
app.get("/flutter/setcmd", (req, res) => {
	let query = req.query;
	let signal = {
		val_1: query.val_1 || 0,
		val_2: query.val_2 || 0,
		val_3: query.val_3 || 0,
	};
	dbTool.insert(
		"insert into `cmd`(val_1,val_2,val_3,cmd_time) values(?,?,?,?)",
		[signal.val_1, signal.val_2, signal.val_3, getDate(true)],
		(res, fields) => {
			dbTool.query("select max(cmd_id) m from `cmd`", (data) => {
				console.log("插入成功 cmd_id is " + data[0].m);
			});
		}
	);
	console.log("————————————Respond———flutter_setcmd—————————————————————————");
	// console.log("query  is " + JSON.stringify(query));
	console.log("signal is " + JSON.stringify(signal));
	console.log("——————————————————Over———————————————————————————————————————");
	res.send("/flutter/setcmd");
});
app.get("*", (req, res) => {
	res.send("欢迎来到任意门");
});
